package ru.spb.osll.myfit.client.widget;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import ru.spb.osll.myfit.common.PageTag;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

/**
 * User: Artem Bukhonov
 * Date: 20.03.12
 * Time: 17:16
 */
public class TagPanelWidget extends Composite {
  private Set<PageTag> m_tags = new TreeSet<PageTag>();
  private HorizontalPanel m_tagLabels = new HorizontalPanel();
  private TagWidgetEventHandler m_eventHandler;
  private boolean m_enabled = false;

  public TagPanelWidget() {
    VerticalPanel tagsPanel = new VerticalPanel();
    initWidget(tagsPanel);
    tagsPanel.add(m_tagLabels);

  }

  private void refresh() {
    m_tagLabels.clear();
    for (PageTag tag : m_tags) {
      TagWidget tagWidget = new TagWidget(tag, new TagWidgetEventHandler() {
        @Override
        public void onTagRemove(PageTag tag) {
          m_tags.remove(tag);
          if (m_eventHandler != null) {
            m_eventHandler.onTagRemove(tag);
          }
        }

        @Override
        public void onTagAdd(PageTag tag) {
          m_tags.add(tag);
          if (m_eventHandler != null) {
            m_eventHandler.onTagAdd(tag);
          }
        }
      });
      tagWidget.setEnabled(m_enabled);
      m_tagLabels.add(tagWidget);
    }
  }

  /*
  Tries to add new tag and return true on success and false if such tag already exists
   */
  public boolean createNewTag(String tagLabel) {
    PageTag pageTag = new PageTag(tagLabel);
    if (m_tags.contains(pageTag)) {
      return false;
    }
    m_tags.add(pageTag);
    if (m_eventHandler != null)
      m_eventHandler.onTagAdd(pageTag);
    refresh();
    return true;
  }

  public void setTags(final Set<PageTag> tags) {
    m_tags.clear();
    m_tags.addAll(tags);
    refresh();
  }

  public Set<PageTag> getTags() {
    return Collections.unmodifiableSet(m_tags);
  }

  public void setEventHandler(TagWidgetEventHandler eventHandler) {
    m_eventHandler = eventHandler;
  }

  public void setEnabled(boolean enabled) {
    m_enabled = enabled;
    for (int i = 0; i < m_tagLabels.getWidgetCount(); ++i) {
      TagWidget widget = (TagWidget) m_tagLabels.getWidget(i);
      widget.setEnabled(enabled);
    }
  }
}
